#tool "nuget:?package=xunit.runner.console"
#tool "nuget:?package=GitVersion.CommandLine"
#tool "nuget:?package=OctopusTools"
#tool "nuget:?package=MSBuild.SonarQube.Runner.Tool"
#addin "nuget:?package=Cake.Sonar"

///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////

var target        = Argument("target", "Default");
var configuration = Argument("Configuration", "Debug");

///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////

var isLocalBuild             = BuildSystem.IsLocalBuild;
var gitVersion				 = GitVersion();
var releaseNumber       	 = gitVersion.NuGetVersion;
var branch              	 = gitVersion.BranchName.ToLowerInvariant();
var solution                 = "Computing.sln";
var octopusDeployProjectName = "GA.EsgComputing";
var octopusDeployServer      = "http://10.120.120.11:8082";
var octopusDeployApiKey      = "API-MBFQMNHSNQE2OQHPSBIQH3MKEY";
var buildFolder              = isLocalBuild ? "./../" : "./../";
var nugetPackageDir          = buildFolder+"artifacts";
var sonarLogin               = "admin";
var sonarPassword            = "Calling!3";
var sonarKey                 = "GA.ESGComputing";
var sonarBranch              = "develop";
var sonarName                = "GA.ESGComputing";
var shouldCreateRelease 	 = branch == "master" || branch == "develop" || branch.StartsWith("release") || branch.StartsWith("hotfix");


///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////

int taskCounter  = 0;
var launcherName = "Launcher";
var buildDir     = buildFolder+"Sustainalytics.ESGComputing.Service/bin/" + configuration;

///////////////////////////////////////////////////////////////////////////////
// TASK DEFINITIONS
///////////////////////////////////////////////////////////////////////////////

TaskSetup(taskSetupContext => {
  var task = taskSetupContext.Task;
  Information("Executing Task {0} of {1} (Name: {2})", ++taskCounter, Tasks.Count, task.Name);
});

if (BuildSystem.IsRunningOnTeamCity) {
  TeamCity.SetBuildNumber(releaseNumber);
}

Task("Clean")
  .WithCriteria(() => isLocalBuild)
  .Does(() => MSBuild(buildFolder + solution, new MSBuildSettings {
    Configuration = configuration,
    MSBuildPlatform = MSBuildPlatform.Automatic,
    ArgumentCustomization = args => args.Append("/t:Clean;Rebuild")
  }));

Task("NuGetRestore")
  .Does(() => NuGetRestore(buildFolder + solution));

Task("SonarBegin")
  .WithCriteria(HasArgument("sonar"))
  .Does(() => {
     SonarBegin(new SonarBeginSettings {
        Url = "http://10.120.120.11:9000",
        Login = sonarLogin,
        Password = sonarPassword,
        Verbose = true,
        Key = sonarKey,
        Branch = sonarBranch,
        Name = sonarName,
     });
  });

Task("Build")
  .IsDependentOn("Clean")
  .IsDependentOn("NuGetRestore")
  .Does(() => MSBuild(buildFolder + solution, new MSBuildSettings {
    NodeReuse = false,
    Configuration = configuration,
    MSBuildPlatform = MSBuildPlatform.Automatic,
    PlatformTarget = PlatformTarget.MSIL,
    ArgumentCustomization = args => args
    .Append("/maxcpucount:4")
  }));

Task("SonarEnd")
  .WithCriteria(HasArgument("sonar"))
  .Does(() => {
     SonarEnd(new SonarEndSettings{
        Login = sonarLogin,
        Password = sonarPassword,
     });
  });

Task("Copy")
  .Does(() => {
    var copyFrom = GetFiles(buildFolder+"Sustainalytics.ESGComputing.Launcher/bin/x64/" + configuration + "/*.*");
    var copyTo = buildDir + "/Launcher";
    EnsureDirectoryExists(copyTo);
    CopyFiles(copyFrom, copyTo);
  });

Task("NuGetPack")
.Does(() => {
    var nuGetPackSettings = new NuGetPackSettings {
      Id = "Sustainalytics.ESGComputing.Service",
      BasePath = buildDir,
      OutputDirectory = Directory(nugetPackageDir),
      Version = releaseNumber,
      Authors = new[] { "Sustainalytics" },
      Description = "Sustainalytics.ESGComputing.Service",
      Files = new[] { new NuSpecContent { Source = "*.*"},
                      new NuSpecContent { Source = "Launcher/**"} },
      ArgumentCustomization = args => args.Append("-Prop Configuration=" + configuration),
    };
    EnsureDirectoryExists(nugetPackageDir);
    NuGetPack(nuGetPackSettings);
  });

Task("NuGetPush")
  .WithCriteria(() => !isLocalBuild)
  .Does(() => {
    var packages = GetFiles(nugetPackageDir + "/*.nupkg").ToList();
    Information("Packages count {0}", packages.Count());
    packages.ForEach(package => {
      Information(package.FullPath);
      NuGetPush(package, new NuGetPushSettings {
        Source = octopusDeployServer + "/nuget/packages",
        ApiKey = octopusDeployApiKey,
      });
    });
  });

Task("OctoCreateRelease")
  .Does(() => OctoCreateRelease(octopusDeployProjectName, new CreateReleaseSettings {
    Server = octopusDeployServer,
    ApiKey = octopusDeployApiKey,
    ReleaseNumber = releaseNumber,
    ArgumentCustomization = args => args.Append("--packageversion " + releaseNumber)
  }));

Task("Default")
  .IsDependentOn("SonarBegin")
  .IsDependentOn("Build")
  .IsDependentOn("SonarEnd")
  .IsDependentOn("Copy");

Task("PrepareDeploy")
  .IsDependentOn("Default")
  .IsDependentOn("NuGetPack")
  .IsDependentOn("NuGetPush")
  .IsDependentOn("OctoCreateRelease");

RunTarget(target);
